<?php
/** user cookies class
*	Date:	2011-08-25
*	Author:	fdipzone
*/

class UserCookies{	// class start

	private $hash_key = 'g506jekfJcpBvRFrpcuJeixezgPNyALmOt4_Ut0f3XE-';
	private	$session_obj;

	public function __construct(){
		$this->session_obj = new Session();
	}

	/** 寫入session and cookies
	* @param	String	$name		cookies name
	* @param	Mixed	$data		data
	* @param	int		$expire		expire time
	*/
	public function set($name,$data,$expire=86400){
		$this->session_obj->set($name,$data);
		$data['COOKIEKEY'] = time().randomKey(6);	# 加入變數
		$cookie_data = authcode(json_encode($data),'ENCODE',$this->hash_key);
		setcookie($name,$cookie_data,time()+$expire);
	}


	/** 判斷session是否存在
	* @param	String	$name	cookiesname
	* @param	int		$hold	1:session為空讀取cookie 0:session為空不讀取cookie
	* @return	boolean
	*/
	public function check($name,$hold=1){
		$data = $this->session_obj->get($name);
		if($data==''){
			if($hold==1){
				if(isset($_COOKIE[$name])){
					$usercookie = authcode($_COOKIE[$name],'DECODE',$this->hash_key);
					if($usercookie){
						$data = json_decode($usercookie,true);
						unset($data['COOKIEKEY']);	# 清除變數
						$this->session_obj->set($name,$data);
						return true;
					}
				}else{
					return false;
				}
			}
			return false;
		}
		return true;
	}


	/** 清空session and cookies
	* @param	String	$name	cookiesname
	*/
	public function clear($name){
		$this->session_obj->set($name,'');
		setcookie($name);
	}

}	// class end
?>